# coding:utf-8
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import random
import threading
import time

import imouse_api

api = imouse_api.HttpApi("127.0.0.1")


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


def findimage(deviceID, filename, isClick, offsetX, offsetY, total=5):
    file = open(filename, "rb")
    byte = file.read()
    file.close()
    tmp = False
    for i in range(total):
        ret = api.find_image(deviceID, byte)
        if ret["status"] == 0 and ret["data"]["code"] == 0 and ret["data"]["confidence"] >= 0.9:
            if isClick:
                # api.mouse_movie(deviceID, ret["data"]["result"][0] + offsetX, ret["data"]["result"][1] + offsetY)
                api.click(deviceID, ret["data"]["result"][0] + offsetX, ret["data"]["result"][1] + offsetY, "left", 100)
                time.sleep(0.1)
                api.mouse_movie(deviceID, random.randint(100, 200), random.randint(100, 500))
            tmp = True
            break
        else:
            print("find_image", i, ret)
        time.sleep(0.4)
    return tmp


def findocr(deviceID, ocr, txtLst, isClick):
    for item in ocr["data"]["list"]:
        for txtItem in txtLst:
            if txtItem == item["txt"]:
                if isClick:
                    api.click(deviceID, item["result"][0], item["result"][1], "left")
                return True
    return False


def findocr1(ocr, txt):
    ok = False
    # if ocr["status"] == 0 and ocr["data"]["code"] == 0 and len(ocr["data"]["list"]) > 0:
    for item in ocr["data"]["list"]:
        if item["txt"].find(txt) >= 0:
            ok = True
    return ok


def t2s(t):
    h = 0
    m, s = t.strip().split(":")
    return int(h) * 3600 + int(m) * 60 + int(s)


def ocr_proc(deviceID, ocr):
    findc = findocr1(ocr, "即表示你接受宝箱规则")
    if findc == False:
        return False
    jp = 0
    jp_ren = 0
    timex = 0
    for item in ocr["data"]["list"]:
        if item["result"][0] >= 210 and item["result"][0] <= 230:
            jp = int(item["txt"])
        if item["txt"].find("人可以领取金币") >= 0:
            jp_ren = int(item["txt"][:2])
        if item["result"][0] >= 205 and item["result"][0] <= 209 and item["txt"].find(":") >= 0:
            timex = t2s(item["txt"])
            if timex > 0:
                timex = timex - 3

    print("金币:", jp, "可以领金币数:", jp_ren, "倒计时:", timex)
    if jp > 0 and jp_ren > 0:
        while timex > 5:
            time.sleep(1)
            print("金币:", jp, "可以领金币数:", jp_ren, "倒计时:", timex)
            timex = timex - 1
        findc = False
        while True:
            if not findc:
                findc = findimage(deviceID, "D:/ScreenSrv/iMouse安装包230211/ScreenControl/Screenshot/打开.bmp", True,
                                  0, 0)
                if findc:
                    time.sleep(0.1)
            find = findimage(deviceID, "D:/ScreenSrv/iMouse安装包230211/ScreenControl/Screenshot/确定.bmp", True, 0, 0,
                             1)
            if find:
                break

    return True


def run(deviceID):
    """
    Args:
        deviceID (str): 设备ID

    Returns:
        None

    功能：执行一系列屏幕操作，包括查找图片、OCR识别等

    """
    print(deviceID)
    time.sleep(1.5)

    while True:
        # 查找图片“宝箱.bmp”
        # api.swipe(deviceID, "up", "left", 0.8, sx=320, sy=550)
        find = findimage(deviceID, "D:/ScreenSrv/iMouse安装包230211/ScreenControl/Screenshot/宝箱.bmp", True, 0, 0)
        time.sleep(0.3)

        # 进行OCR识别
        ocr = api.ocr(deviceID, [[352, 50], [352, 74], [382, 50], [382, 74]], True)

        # 判断OCR识别结果是否有效
        if ocr["status"] == 0 and ocr["data"]["code"] == 0 and len(ocr["data"]["list"]) > 0:
            print("在线人数:", ocr["data"]["list"][0]["txt"])

        # 如果找到“宝箱.bmp”图片
        if find:
            # 进行OCR识别
            ocr = api.ocr(deviceID, [[6, 442], [6, 870], [401, 442], [401, 870]], True)

            # 处理OCR识别结果
            # find = findocr1(ocr, "即表示你接受宝箱规则")
            find = ocr_proc(deviceID, ocr)

            # 注意：以下两行代码被注释掉了，无法执行
            # print(find, ocr)
            # if find:

        # 随机等待一段时间
        # time.sleep(random.randint(1, 3))
    return

    # 查找图片“主图标.bmp”
    tmp = findimage(deviceID, "D:/ScreenSrv/ScreenControl/Screenshot/主图标.bmp", True, 0, 0)
    if not tmp:
        return

    time.sleep(2)
    for i in range(4):
        # 执行滑动操作
        api.swipe(deviceID, "up", "left", 0.8, sx=320, sy=550)
        time.sleep(random.randint(3, 5))
        print("swipe", i)

        # 进行OCR识别
        ocr = api.ocr(deviceID, [[5, 547], [5, 628], [273, 547], [273, 628]])

        # 判断OCR识别结果是否有效
        if ocr["status"] == 0 and ocr["data"]["code"] == 0 and len(ocr["data"]["list"]) > 0:
            print("ocr A", ocr["data"]["list"][0]["txt"])

        print("ocr", ocr)

        # 根据随机数执行不同操作
        k = random.randint(1, 5)
        if k == 1 or k == 3 or k == 4:
            findimage(deviceID, "D:/ScreenSrv/ScreenControl/Screenshot/点赞.bmp", True, 0, 0)
            api.mouse_movie(deviceID, 100, random.randint(200, 700))
            time.sleep(1)

    # 进行OCR识别
    ocr = api.ocr(deviceID, [[133, 440], [133, 476], [264, 440], [264, 476]])

    # 判断OCR识别结果是否有效
    if ocr["status"] == 0 and ocr["data"]["code"] == 0 and len(ocr["data"]["list"]) > 0:
        print("ocr", ocr["data"]["list"][0]["txt"])

    print("ocr", ocr)

    # 查找图片“评论.bmp”
    tmp = findimage(deviceID, "D:/ScreenSrv/ScreenControl/Screenshot/评论.bmp", True, 0, 0)
    print("评论", tmp)
    if not tmp:
        return

    time.sleep(1)

    # 查找图片“聊天区.bmp”或“聊天区1.bmp”
    tmp = findimage(deviceID)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

    deviceidLst = []
    deviceidLst.append('88:64:40:06:C6:53')  # 群控多台手机1
    # deviceidLst.append('DC:2B:2A:14:2A:F6')   #群控多台手机2
    # deviceidLst.append('DC:2B:2A:14:2A:F2')   #群控多台手机3
    # deviceidLst.append('DC:2B:2A:14:2A:F3')   #群控多台手机4
    for deviceId in deviceidLst:
        thread1 = threading.Thread(target=run, args=(deviceId,))
        thread1.start()
        time.sleep(1)

    while True:
        cmd = input("请输入:")
        if cmd == "q":
            break

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
